"use client";

import { useState } from "react";
import { useQuery, useMutation, useQueryClient } from "@tanstack/react-query";
import { SiteHeader } from "@/components/site-header";
import { SiteFooter } from "@/components/site-footer";
import { useAuth } from "@/lib/auth-context";
import { redirect, useRouter } from "next/navigation";
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";
import { Card } from "@/components/ui/card";
import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import { Heart, MessageSquare, Clock, Trash2, ExternalLink } from "lucide-react";
import Link from "next/link";
import { getFavoriteList, deleteFavorite } from "@/apis/client/favorite";
import { getChatSessions, deleteChatSession } from "@/apis/client/chat";
import { ContentTypeEnum } from "@/constants";
import { toast } from "sonner";
import { Favorite, FavoriteMenu } from "@/types/favorite";
import { ChatSession } from "@/types/chat";
import Image from "next/image";
import { pickDefaultIconForKey } from "@/constants/default-icons";

export default function ProfilePage() {
  const { user, isLoading: isAuthLoading } = useAuth();
  const queryClient = useQueryClient();
  const router = useRouter();
  const [activeTab, setActiveTab] = useState("favorites");
  const [selectedMenuId, setSelectedMenuId] = useState<string>("all");

  const { data: favoriteData, isLoading: isFavoritesLoading } = useQuery({
    queryKey: ["favorites"],
    queryFn: getFavoriteList,
    enabled: !!user,
  });

  const { data: chatSessions = [], isLoading: isChatSessionsLoading } = useQuery({
    queryKey: ["chatSessions"],
    queryFn: () => getChatSessions(),
    enabled: !!user,
  });

  const deleteFavoriteMutation = useMutation({
    mutationFn: (contentId: string) => deleteFavorite(contentId),
    onSuccess: () => {
      toast.success("已取消收藏");
      queryClient.invalidateQueries({ queryKey: ["favorites"] });
    },
    onError: () => {
      toast.error("操作失败，请重试");
    },
  });

  const deleteChatSessionMutation = useMutation<void, Error, string>({
    mutationFn: deleteChatSession,
    onSuccess: () => {
      toast.success("对话删除成功");
      queryClient.invalidateQueries({ queryKey:  ["chatSessions"] });
    },
    onError: () => {
      toast.error("删除失败，请重试");
    },
  });

  if (isAuthLoading) {
    return (
      <div className="min-h-screen flex flex-col">
        <main className="flex-1 flex items-center justify-center">
          <div className="text-center">
            <div className="animate-spin rounded-full h-12 w-12 border-b-2 border-primary mx-auto mb-4"></div>
            <p className="text-muted-foreground">加载中...</p>
          </div>
        </main>
      </div>
    );
  }

  if (!user) {
    redirect("/login");
  }

  // 获取当前选中菜单的收藏内容
  const currentMenuContents = favoriteData?.menus.find(menu => menu.id === selectedMenuId)?.contents || [];
  const totalFavorites = favoriteData?.total || 0;

  return (
    <div className="min-h-screen flex flex-col">
      <main className="flex-1 bg-background">
        <div className="max-w-[1440px] mx-auto px-4 py-8">
          {/* User Info Section */}
          <Card className="p-6 mb-8">
            <div className="flex items-center gap-4">
              <div className="h-16 w-16 rounded-full bg-primary flex items-center justify-center text-primary-foreground text-2xl font-bold">
                {(user.username || user.nickname)?.charAt(0)}
              </div>
              <div className="flex-1">
                <h1 className="text-2xl font-bold mb-1">{user.nickname || user.username}</h1>
                <p className="text-muted-foreground">{user.email}</p>
              </div>
              <div className="flex gap-8 text-center">
                <div>
                  <div className="text-2xl font-bold text-primary">{totalFavorites}</div>
                  <div className="text-sm text-muted-foreground">收藏</div>
                </div>
                <div>
                  <div className="text-2xl font-bold text-primary">{chatSessions.length}</div>
                  <div className="text-sm text-muted-foreground">对话</div>
                </div>
              </div>
            </div>
          </Card>

          {/* Tabs Section */}
          <Tabs value={activeTab} onValueChange={setActiveTab} className="w-full">
            <TabsList className="grid w-full max-w-md grid-cols-2">
              <TabsTrigger value="favorites">我的收藏</TabsTrigger>
              <TabsTrigger value="chat">对话记录</TabsTrigger>
            </TabsList>

            {/* Favorites Tab */}
            <TabsContent value="favorites" className="mt-6">
              {/* Dynamic Menu Filter Buttons */}
              <div className="flex gap-2 mb-6 flex-wrap">
                {favoriteData?.menus.map((menu) => (
                  <Button
                    key={menu.id}
                    variant={selectedMenuId === menu.id ? "default" : "outline"}
                    size="sm"
                    onClick={() => setSelectedMenuId(menu.id)}
                  >
                    {menu.name} ({menu.contents.length})
                  </Button>
                ))}
              </div>

              {/* Favorites List */}
              {isFavoritesLoading ? (
                <div className="text-center text-muted-foreground">正在加载收藏...</div>
              ) : currentMenuContents.length === 0 ? (
                <div className="text-center text-muted-foreground py-12">
                  <Heart className="mx-auto h-12 w-12 text-gray-400" />
                  <h3 className="mt-2 text-sm font-medium text-gray-900">暂无收藏</h3>
                  <p className="mt-1 text-sm text-gray-500">快去发现喜欢的内容吧！</p>
                </div>
              ) : (
                <div className="grid gap-4">
                  {currentMenuContents.map((item) => (
                    <Card key={item.id} className="p-4 hover:shadow-md transition-shadow">
                      <div className="flex gap-4">
                        {item.content.type === ContentTypeEnum.TOOL ? (
                          <div className="h-16 w-16 rounded-lg overflow-hidden bg-muted flex-shrink-0">
                            <Image
                              src={
                                item.content.icon && item.content.icon.startsWith("http")
                                  ? item.content.icon
                                  : pickDefaultIconForKey(item.content.title)
                              }
                              alt={item.content.title}
                              width={64}
                              height={64}
                              className="h-16 w-16 object-cover"
                            />
                          </div>
                        ) : (
                          <div className="h-16 w-16 rounded-lg overflow-hidden bg-muted flex-shrink-0">
                            <Image
                              src={item.content.cover || pickDefaultIconForKey(item.content.title)}
                              alt={item.content.title}
                              width={64}
                              height={64}
                              className="h-16 w-16 object-cover"
                            />
                          </div>
                        )}
                        <div className="flex-1 min-w-0">
                          <div className="flex items-start justify-between gap-2 mb-2">
                            <div className="flex items-center gap-2">
                              <Badge variant={item.content.type === ContentTypeEnum.TOOL ? "default" : "secondary"}>
                                {item.content.type === ContentTypeEnum.WEBSITE ? "凯笙导航" : item.content.type === ContentTypeEnum.TOOL ? "AI工具" : "资讯"}
                              </Badge>
                              <h3 className="font-semibold truncate">{item.content.title}</h3>
                            </div>
                            <div className="flex gap-1 flex-shrink-0">
                              <Button
                                variant="ghost"
                                size="icon"
                                className="h-8 w-8 text-red-500 hover:text-red-600"
                                onClick={() => deleteFavoriteMutation.mutate(item.contentId)}
                                disabled={deleteFavoriteMutation.isPending}
                              >
                                <Trash2 className="h-4 w-4" />
                              </Button>
                              <Link href={`/contentDetail?id=${item.content.id}`} passHref>
                                <Button variant="ghost" size="icon" className="h-8 w-8">
                                  <ExternalLink className="h-4 w-4" />
                                </Button>
                              </Link>
                            </div>
                          </div>
                          <p className="text-sm text-muted-foreground truncate">{item.content.description}</p>
                          <div className="flex items-center justify-between text-xs text-muted-foreground mt-2">
                            <div className="flex items-center gap-1">
                              <Clock className="h-3 w-3" />
                              <span>收藏于 {new Date(item.createdAt).toLocaleDateString()}</span>
                            </div>
                          </div>
                        </div>
                      </div>
                    </Card>
                  ))}
                </div>
              )}
            </TabsContent>

            {/* Chat History Tab */}
            <TabsContent value="chat" className="mt-6">
              {isChatSessionsLoading ? (
                <div className="text-center text-muted-foreground">正在加载对话记录...</div>
              ) : chatSessions.length === 0 ? (
                <div className="text-center text-muted-foreground py-12">
                  <MessageSquare className="mx-auto h-12 w-12 text-gray-400" />
                  <h3 className="mt-2 text-sm font-medium text-gray-900">暂无对话</h3>
                  <p className="mt-1 text-sm text-gray-500">开始一段新的对话吧！</p>
                </div>
              ) : (
                <div className="grid gap-4">
                  {chatSessions.map((chat) => {
                    const avatarSrc = chat.content?.cover?.url || pickDefaultIconForKey(chat.content?.title || chat.title);
                    return (
                      <Card key={chat.id} className="p-4 hover:shadow-md transition-shadow">
                        <div className="flex items-start justify-between gap-4">
                          <div className="flex items-center gap-4 flex-1 min-w-0">
                            <div className="h-12 w-12 rounded-lg overflow-hidden bg-muted flex-shrink-0">
                              <Image
                                src={avatarSrc}
                                alt={chat.title}
                                width={48}
                                height={48}
                                className="h-12 w-12 object-cover"
                              />
                            </div>
                            <div className="flex-1 min-w-0">
                              <h3 className="font-semibold mb-2 truncate">{chat.title}</h3>
                              <div className="flex items-center justify-between text-xs text-muted-foreground">
                                <div className="flex items-center gap-1">
                                  <MessageSquare className="h-3 w-3" />
                                  <span>{chat._count?.messages ?? chat.messageCount} 条消息</span>
                                </div>
                                <div className="flex items-center gap-1">
                                  <Clock className="h-3 w-3" />
                                  <span>{new Date(chat.updatedAt).toLocaleString()}</span>
                                </div>
                              </div>
                            </div>
                          </div>
                          <div className="flex flex-col gap-2 flex-shrink-0">
                            <Button
                              variant="outline"
                              size="sm"
                              onClick={() => router.push(`/chat?chatId=${chat.chatId}${chat.agentId ? `&contentId=${chat.contentId}` : ""}`)}
                            >
                              继续对话
                            </Button>
                            <Button
                              variant="ghost"
                              size="sm"
                              className="text-red-500 hover:text-red-600"
                              onClick={() => deleteChatSessionMutation.mutate(chat.chatId)}
                              disabled={deleteChatSessionMutation.isPending}
                            >
                              <Trash2 className="h-4 w-4 mr-1" />
                              删除
                            </Button>
                          </div>
                        </div>
                      </Card>
                    );
                  })}
                </div>
              )}
            </TabsContent>
          </Tabs>
        </div>
      </main>
    </div>
  );
}
